package client;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class InputConsole {

    private static final int defaultPort = 9999;
    private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static InputConsole input = new InputConsole();
    private DataOutputStream out;
    private int port;

    public static void main(String[] args) {

        input.getArguments();
        input.connectWithOutputConsole();

    }

    public Socket connectWithOutputConsole() {
        while (true) {
            try {
                System.out.println("Waiting for output console...");
                ServerSocket ss = new ServerSocket(port);
                Socket sock = ss.accept();
                System.out.println("Connected to output console!");
                out = new DataOutputStream(sock.getOutputStream());
                return sock;
            } catch (IOException e) {

                System.out.println("Can't connect with output console due:");
                System.out.println(e.toString());

                boolean flag = true;
                while (flag) {
                    System.out.println("Exit(\"e\") or try to reconnect(\"r\")?");
                    String input = "e";
                    try {
                        input = reader.readLine();
                    } catch (IOException ignored) {
                    }
                    switch (input) {
                        case ("e"):
                            System.out.println("Exit");
                            System.exit(0);
                            break;
                        case ("r"):
                            flag = false;
                            break;
                        default:
                    }
                }
            }
        }
    }


    public void sendOutput(String output) {
        try {
            out.writeUTF(output);
            out.flush();
        } catch (IOException e) {
            System.out.println("Output console was closed!");
            System.out.println("Exit");
            System.exit(1);
        }

    }

    public void getArguments(String... args) {
        if (args.length != 1) {
            this.setDefaultPort();
        } else {
            try {
                this.port = Integer.parseUnsignedInt(args[0]);
            } catch (NumberFormatException e) {
                this.setDefaultPort();
            }
        }
    }

    private void setDefaultPort() {
        System.out.println("Warning: port number not set, using " + defaultPort + " for internal communication");
        this.port = defaultPort;
    }
}
